package com.gwz.cardserver.logic;

import com.alibaba.fastjson.JSON;
import com.gwz.cardserver.consts.AccountCodeConst;
import com.gwz.cardserver.dto.ReqBase;
import com.gwz.cardserver.dto.ResBase;
import com.gwz.cardserver.dto.account.AccountDto;
import com.gwz.cardserver.entity.Account;
import com.gwz.cardserver.service.AccountService;
import io.netty.channel.ChannelHandlerContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 账号处理Handler
 */
@Component("AccountHandler")
public class AccountHandler implements IHandler {
    @Autowired
    private AccountService accountService;

    @Override
    public void channelRead(ChannelHandlerContext ctx, ReqBase reqBase) {
        switch (reqBase.getSubCode()) {
            case AccountCodeConst.REGIST: {
                AccountDto accountDto = JSON.parseObject(reqBase.getMessage(), AccountDto.class);
                String regist = accountService.regist(accountDto, ctx, reqBase);
                ctx.writeAndFlush(ResBase.success(reqBase, "注册成功"));
                break;
            }

            case AccountCodeConst.LOGIN: {
                AccountDto accountDto = JSON.parseObject(reqBase.getMessage(), AccountDto.class);
                accountService.login(accountDto, ctx, reqBase);
                ctx.writeAndFlush(ResBase.success(reqBase, "登录成功"));
                break;
            }
            case AccountCodeConst.GET_USER: {
                Account account = accountService.getById(ctx);
                ctx.writeAndFlush(ResBase.success(reqBase, JSON.toJSONString(account)));
                break;
            }
            case AccountCodeConst.SET_NAME:{
                accountService.setName(reqBase.getMessage(),ctx);
                ctx.writeAndFlush(ResBase.success(reqBase, reqBase.getMessage()));
                break;
            }
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        accountService.offline(ctx);
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        accountService.removeUserByChannel(ctx);
    }
}
